package com.ibm.cps.redis;

import com.ibm.util.LocalConfig;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * store the schemaid for processor
 * @author Jingjing Wang
 *2015-4-19
 */
public class ProcessorSchemaRedis {

	private String redisHost;
	private int redisPort;
	private JedisPool pool;
	private Jedis connection;
	private static ProcessorSchemaRedis processorSchemaRedis = null;
	private static final String PREFIX = "processor";
	private static final String USERID = "tenantid";
	private static final String SCHEMAID = "schemaid";

	public static ProcessorSchemaRedis getProcessorSchemaRedis() {
		if (processorSchemaRedis == null)
			processorSchemaRedis = new ProcessorSchemaRedis(
					LocalConfig.REDIS_SERVER_HOST,
					LocalConfig.REDIS_SERVER_PORT);
		return processorSchemaRedis;
	}

	public ProcessorSchemaRedis(String redisHost, int redisPort) {
		this.redisHost = redisHost;
		this.redisPort = redisPort;
		pool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort);
	}

	public String constructKey(String key) {
		return PREFIX + "_" + key;
	}

	public boolean putProcessorSchema(String processor, String tenantid,
			String schemaid) {
		connection = pool.getResource();
		String key = constructKey(processor);
		connection.hset(key, USERID, tenantid);
		connection.hset(key, SCHEMAID, schemaid);
		pool.returnResource(connection);
		return true;
	}

	public String getProcessSchema(String processor) {
		connection = pool.getResource();
		String key = constructKey(processor);
		String schemaid = connection.hget(key, SCHEMAID);
		pool.returnResource(connection);
		return schemaid;
	}

	public String getProcessorUser(String processor) {
		connection = pool.getResource();
		String key = constructKey(processor);
		String tenantid = connection.hget(key, USERID);
		pool.returnResource(connection);
		return tenantid;
	}
}
